{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv, find_dotenv\n",
    "\n",
    "# 读取本地/项目的环境变量。\n",
    "\n",
    "# find_dotenv() 寻找并定位 .env 文件的路径\n",
    "# load_dotenv() 读取该 .env 文件，并将其中的环境变量加载到当前的运行环境中  \n",
    "# 如果你设置的是全局的环境变量，这行代码则没有任何作用。\n",
    "_ = load_dotenv(find_dotenv())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json\n",
    "import os\n",
    "def wenxin_embedding(text: str):\n",
    "    # 获取环境变量 wenxin_api_key、wenxin_secret_key\n",
    "    api_key = os.environ['QIANFAN_AK']\n",
    "    secret_key = os.environ['QIANFAN_SK']\n",
    "\n",
    "    # 使用API Key、Secret Key向https://aip.baidubce.com/oauth/2.0/token 获取Access token\n",
    "    url = \"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}\".format(api_key, secret_key)\n",
    "    payload = json.dumps(\"\")\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Accept': 'application/json'\n",
    "    }\n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "    \n",
    "    # 通过获取的Access token 来embedding text\n",
    "    url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings/embedding-v1?access_token=\" + str(response.json().get(\"access_token\"))\n",
    "    input = []\n",
    "    input.append(text)\n",
    "    payload = json.dumps({\n",
    "        \"input\": input\n",
    "    })\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json'\n",
    "    }\n",
    "\n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "\n",
    "    return json.loads(response.text)\n",
    "# text应为List(string)\n",
    "text = \"要生成 embedding 的输入文本，字符串形式。\"\n",
    "response = wenxin_embedding(text=text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "本次embedding id为：as-k3yg65gner\n",
      "本次embedding产生时间戳为：1733299386\n"
     ]
    }
   ],
   "source": [
    "print('本次embedding id为：{}'.format(response['id']))\n",
    "print('本次embedding产生时间戳为：{}'.format(response['created']))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "返回的embedding类型为:embedding_list\n",
      "embedding长度为：384\n",
      "embedding（前10）为：[0.060567744076251984, 0.020958080887794495, 0.053234219551086426, 0.02243831567466259, -0.024505289271473885, -0.09820500761270523, 0.04375714063644409, -0.009092536754906178, -0.020122773945331573, 0.015808865427970886]\n"
     ]
    }
   ],
   "source": [
    "print('返回的embedding类型为:{}'.format(response['object']))\n",
    "print('embedding长度为：{}'.format(len(response['data'][0]['embedding'])))\n",
    "print('embedding（前10）为：{}'.format(response['data'][0]['embedding'][:10]))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "jupyter38",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
